import { HttpStatus, Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { InjectRepository } from '@nestjs/typeorm';
import { jwtConstants } from 'src/auth/constants';
import { Sort } from 'src/sorts/sorts.entity';
import { Tag } from 'src/tags/tags.entity';
import { Repository } from 'typeorm';
import { Blog } from './blog.entity';
import { CreateBlogDto } from './dto/create-blog.dto';
import { UpdateBlogDto } from './dto/update-blog.dto';

@Injectable()
export class BlogService {
  constructor(
    private readonly jwtService: JwtService,
    @InjectRepository(Blog)
    private blogRepository: Repository<Blog>,
    @InjectRepository(Tag)
    private tagRepository: Repository<Tag>,
    @InjectRepository(Sort)
    private sortRepository: Repository<Sort>,
  ) {}
  async create(createBlogDto: CreateBlogDto, token: string) {
    const { content, sorts, tags } = createBlogDto;
    const { id } = this.jwtService.verify(token, {
      secret: jwtConstants.secret,
    });
    const obj = {
      content,
      sorts,
      tags,
      user: id,
    };
    return this.blogRepository
      .save(obj as any)
      .then(() => {
        return {
          code: HttpStatus.OK,
          message: '发布成功!',
        };
      })
      .catch((error) => {
        return {
          code: HttpStatus.INTERNAL_SERVER_ERROR,
          message: error.message,
        };
      });
  }

  async findAll() {
    const blogs: any = await this.blogRepository.find();
    const tags = await this.tagRepository.find();
    const sorts = await this.sortRepository.find();
    blogs.forEach((item: any, index: number | string) => {
      blogs[index].sorts = item.sorts.split(',');
      blogs[index].tags = item.tags.split(',');
      const tagArr = [];
      const sortsArr = [];
      item.sorts.forEach((item: any) => {
        tags.forEach((tagItem) => {
          if (tagItem.id == item) {
            tagArr.push(tagItem.tagName);
          }
        });
      });
      item.tags.forEach((item: any, index: number | string) => {
        sorts.forEach((sortItem) => {
          if (sortItem.id == item) {
            sortsArr.push(sortItem.sortName);
          }
        });
      });
      blogs[index].tags = tagArr.toString();
      blogs[index].sorts = sortsArr.toString();
    });
    return {
      code: HttpStatus.OK,
      data: blogs,
    };
  }

  async findOne(id: number) {
    const blog = await this.blogRepository.findOne(id);
    // 查看次数递增
    blog.views++;
    await this.blogRepository.save(blog);

    // 标签和类名的ID转换成name
    const tags = await this.tagRepository.find();
    const sorts = await this.sortRepository.find();
    const blogSortsArr = blog.sorts.split(',');
    const blogTagsArr = blog.tags.split(',');
    const tagArr = [];
    const sortsArr = [];
    blogSortsArr.forEach((item: any) => {
      sorts.forEach((sortItem) => {
        if (sortItem.id == item) {
          sortsArr.push(sortItem.sortName);
        }
      });
    });
    blogTagsArr.forEach((item: any) => {
      tags.forEach((tagItem) => {
        if (tagItem.id == item) {
          tagArr.push(tagItem.tagName);
        }
      });
    });
    blog.sorts = sortsArr.toString();
    blog.tags = tagArr.toString();
    if (!blog) {
      return {
        code: HttpStatus.INTERNAL_SERVER_ERROR,
        message: '该博客不存在！',
      };
    }

    return {
      code: HttpStatus.OK,
      data: blog,
    };
  }

  update(id: number, updateBlogDto: UpdateBlogDto) {
    return `This action updates a #${id} blog`;
  }

  remove(id: number) {
    return `This action removes a #${id} blog`;
  }
}
